package com.dh.web.controller;

import com.dh.core.config.Constant;
import com.dh.core.util.DateUtil;
import com.dh.core.util.OssUploadUtils;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/image")
public class ImageUploadController {

    @RequestMapping(value = "upload", method = RequestMethod.POST)
    @RequiresUser
    @ResponseBody
    public Map<String, Object> create(@RequestParam MultipartFile uploadImgFile) {
        Map<String, Object> map = new HashMap<>();
        try {
            try {
                byte[] data = uploadImgFile.getBytes();

                String name = uploadImgFile.getOriginalFilename();
                if (name.indexOf(".") > 0) {
                    name = name.substring(name.lastIndexOf("."));
                }

                String key = Constant.OSS_BASE_PATH + DateUtil.getCurrentYMHMS() + name;
                OssUploadUtils.uploadFile(data, Constant.ImageFileType, key);
                map.put("success", true);
                String url = Constant.OSS_DOMAIN_URL +"/" + key;
                map.put("image", url);
                map.put("file_path", url);
                map.put("msg", "上传成功");
                return map;
            } catch (Exception e) {
                e.printStackTrace();
                map.put("msg", "上传失败");
            }
        } catch (Exception e) {
            map.put("msg", "图片上传发生错误。");
        }

        map.put("success", false);
        return map;
    }
}
